﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;

namespace JamendoSearchREST
{
    public partial class MainPage : System.Web.UI.Page
    {

        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void btnRequest_Click(object sender, EventArgs e)
        {
            string query = tbQuery.Text.Replace(' ', '+').Replace(',', '+');
            string xmlResponse;

            lblResult.Text = "";

            WebRequest req = WebRequest.Create(@"http://api.jamendo.com/v3.0/tracks/?client_id=39baa3cf&format=xml&limit=5&namesearch=" + query + "&include=musicinfo+stats");
            req.Method = "GET";

            HttpWebResponse resp = req.GetResponse() as HttpWebResponse;
            if (resp.StatusCode == HttpStatusCode.OK)
            {               
                using (Stream respStream = resp.GetResponseStream())
                {
                    StreamReader reader = new StreamReader(respStream, Encoding.UTF8);
                    xmlResponse = reader.ReadToEnd();
                }

                using (XmlReader reader = XmlReader.Create(new StringReader(xmlResponse)))
                {
                    while (reader.ReadToFollowing("artist_name"))
                    {
                        string artistName = reader.ReadElementContentAsString();
                        reader.ReadToFollowing("name");
                        string songTitle = reader.ReadElementContentAsString();
                        reader.ReadToFollowing("audio");
                        string audio = reader.ReadElementContentAsString();

                        lblResult.Text += "<div>" +  
                                                "<p><b>Artist name:</b> " + artistName + "</br>" +
                                                "<b>Song title:</b> " + "<a href=\"" + audio + "\">" + songTitle + "</a></p>" +
                                          "</div>";                                      
                    }
                }

            }
            else
            {
                lblResult.Text = string.Format("Status Code: {0}, Status Description: {1}", resp.StatusCode, resp.StatusDescription);
            }
            
        }
    }
}